<!DOCTYPE html>
<html lang="zh">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            .outer {
                width: 640px;
                margin: 50px auto;
                text-align: center;
            }
        </style>
        <script>
            window.onload = function () {
                /* 
                    点击按钮切换图片
                */

                // 获取info
                const info = document.getElementById("info")

                // 获取到图片
                const img = document.getElementsByTagName("img")[0]

                // 获取两个按钮
                const prev = document.getElementById("prev")
                const next = document.getElementById("next")

                // 创建一个数组来存储图片的路径
                const imgArr = [
                    "./images/1.png",
                    "./images/2.png",
                    "./images/3.png",
                    "./images/4.png",
                    "./images/5.png",
                ]

                // 创建一个变量记录当前图片的索引
                let current = 0

                info.textContent = `总共 ${imgArr.length} 张图片，当前第 ${current + 1} 张`

                // 上一张
                prev.onclick = function () {
                    current--

                    //检查current的值是否合法
                    if(current < 0){
                        // current = 0
                        current = imgArr.length - 1
                    }

                    img.src = imgArr[current]

                    info.textContent = `总共 ${imgArr.length} 张图片，当前第 ${current + 1} 张`

                }

                // 点击next按钮后，切换图片
                next.onclick = function () {
                    current++

                    if(current > imgArr.length - 1){
                        // current = imgArr.length - 1
                        current = 0
                    }

                    // 切换图片 --> 2.png 就是修改img的src属性
                    img.src = imgArr[current]

                    info.textContent = `总共 ${imgArr.length} 张图片，当前第 ${current + 1} 张`

                }
                
            }
        </script>
    </head>
    <body>
        <div class="outer">
            <p id="info">
                总共n张图片，当前第m张        
            </p>
            <div class="img-wrapper">
                <img src="./images/1.png" alt="这是一个图片" />
            </div>

            <div class="btn-wrapper">
                <button id="prev">上一张</button>
                <button id="next">下一张</button>
            </div>
        </div>
    </body>
</html>
